<template>
  <!-- 知识库-文档管理 -->
  <div class="document-management">
    <a-card class="row-one" title="常用">
      <div class="row-one-box">
        <div
          class="item"
          v-for="item in commonKnowledgeBase"
          :key="item"
          @click="clickOperation('下载', item)"
        >
          <div class="icon">
            <FolderOutlined />
          </div>
          <div class="text">{{ item.fileName }}</div>
        </div>
      </div>
    </a-card>
    <div class="row-two">
      <a-card class="row-two-left">
        <div class="input-box">
          <a-input
            class="input"
            placeholder="请输入目录名"
            v-model:value="formKnowledgeBaseFolder.documentName"
          ></a-input>
          <a-button class="button" @click="clickQueryKnowledgeBaseFolder">
            <SearchOutlined />
          </a-button>
        </div>
        <a-directory-tree
          v-model:expandedKeys="expandedKeys"
          v-model:selectedKeys="selectedKeys"
          multiple
          :tree-data="treeData"
          @select="clickTreeNode"
        >
          <template #title="{ key, title }">
            <div class="tree-item">
              {{ title }}
              <PlusOutlined
                class="icon"
                @click.stop="clickAddKnowledgeBaseFolder('新增', key, title)"
              />
              <EditOutlined
                v-if="key !== 0"
                class="icon"
                @click.stop="clickAddKnowledgeBaseFolder('编辑', key, title)"
              />
              <a-popconfirm
                title="确认删除吗？"
                ok-text="确认"
                cancel-text="取消"
                @confirm="clickDelKnowledgeBaseFolder(key)"
                @click.stop
              >
                <DeleteOutlined v-if="key !== 0" class="icon" />
              </a-popconfirm>
            </div>
          </template>
        </a-directory-tree>
      </a-card>
      <div class="row-two-right">
        <a-card class="query" title="文件查询">
          <div class="input-box">
            <div class="item">
              <div class="text">文件名称</div>
              <a-input
                class="input"
                placeholder="请输入"
                v-model:value="formKnowledgeBaseFileList.fileName"
              >
              </a-input>
            </div>
            <div class="item">
              <div class="text">创建人</div>
              <a-input
                class="input"
                placeholder="请输入"
                v-model:value="formKnowledgeBaseFileList.createBy"
              >
              </a-input>
            </div>
            <div class="item item-time">
              <div class="text">创建时间</div>
              <a-range-picker
                class="input picker"
                show-time
                v-model:value="formKnowledgeBaseFileList.valueRangePicker"
                @change="changeRangePicker"
              />
            </div>
            <div class="item">
              <a-button class="button" @click="clickReset">重置</a-button>
              <a-button type="primary" @click="clickQuery">查询</a-button>
            </div>
          </div>
        </a-card>
        <a-card class="list" :title="listTitle">
          <template #extra>
            <div class="button-box">
              <a-button
                class="button"
                type="primary"
                @click="clickCreateFile"
                :disabled="disabledUploadTheKnowledgeBaseFile"
                >新建文件
              </a-button>
              <a-upload
                class="button"
                v-model:file-list="fileList"
                name="file"
                :showUploadList="false"
                :data="dataUploadTheKnowledgeBaseFile"
                :action="rootUrl + api.uploadTheKnowledgeBaseFileUrl"
                :headers="headers"
                @change="changeUploadTheKnowledgeBaseFileUrl"
              >
                <a-button
                  class="button"
                  :disabled="disabledUploadTheKnowledgeBaseFile"
                  >上传文件</a-button
                >
              </a-upload>
            </div>
          </template>
          <a-table
            class="table"
            :pagination="false"
            :columns="columns"
            :data-source="tableData"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'operation'">
                <div class="operation">
                  <span @click="clickOperation('查看', record)">查看</span>
                  <span @click="clickOperation('下载', record)">下载</span>
                  <span @click="clickOperation('编辑', record)">编辑</span>
                  <span @click="clickOperation('删除', record)">删除</span>
                  <span
                    v-show="record.isCollect"
                    @click="clickOperation('收藏', record)"
                    >已收藏</span
                  >
                  <span
                    v-show="!record.isCollect"
                    @click="clickOperation('收藏', record)"
                    >收藏</span
                  >
                </div>
              </template>
            </template>
          </a-table>
          <a-pagination
            v-model:current="formKnowledgeBaseFileList.pageNum"
            v-model:pageSize="formKnowledgeBaseFileList.pageSize"
            :total="formKnowledgeBaseFileList.total"
            show-less-items
            @change="changePagination"
          />
        </a-card>
      </div>
    </div>
    <a-modal
      class="modal"
      wrapClassName="document-management"
      v-model:open="openFolder"
      :title="modalTitle + '目录'"
      @ok="clickModalOk"
      @cancel="clickModalCancel"
    >
      <div class="item">
        <div class="label">目录名称</div>
        <a-input
          class="input"
          placeholder="请输入目录名称"
          v-model:value="formAddEditKnowledgeBaseFolder.name"
        ></a-input>
      </div>
    </a-modal>
    <CreateFileModal
      :open="openCreateFileModal"
      :info="infoCreateFileModal"
      @cancel="cancelCreateFileModal"
      @updatePage="updatePage"
    ></CreateFileModal>
  </div>
</template>
<script setup lang="ts">
  // 引入组件
  // 引入方法
  import commonMethod from '@/common-method/common-method'
  import { defineProps, defineEmits, watch, onMounted, ref } from 'vue'
  import {
    FolderOutlined,
    SearchOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
  } from '@ant-design/icons-vue'
  import api from '@/axios/api'
  import { message } from 'ant-design-vue'
  import CreateFileModal from './components/CreateFileModal.vue'
  import { useRouter } from 'vue-router'
  const props = defineProps({})
  const emits = defineEmits([])
  // 自定义状态
  const router = useRouter()
  const expandedKeys = ref([0])
  const selectedKeys = ref([0])
  const treeData = ref([])
  const listTitle = ref('文件列表')
  const columns = [
    { title: '文件名称', dataIndex: 'fileName' },
    { title: '创建时间', dataIndex: 'createTime', width: 200 },
    { title: '创建人', dataIndex: 'createBy', width: 100 },
    { title: '更新时间', dataIndex: 'updateTime', width: 200 },
    { title: '更新人', dataIndex: 'updateBy', width: 100 },
    { title: '操作', dataIndex: 'operation', width: 250 },
  ] //列表配置
  const tableData = ref([]) //列表数据
  const openFolder = ref(false) //文件夹对话框状态
  const formKnowledgeBaseFolder = ref({
    documentName: undefined,
    documentType: 1,
  }) //知识库文件夹表单
  const formAddEditKnowledgeBaseFolder = ref({
    id: undefined,
    parentId: undefined,
    name: undefined,
    documentType: 1,
  }) //新增修改知识库文件夹表单
  const formKnowledgeBaseFileList = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0,
    documentId: undefined,
    fileName: undefined, //文件名称
    createBy: undefined, //创建人
    startTime: undefined, //开始时间
    endTime: undefined, //结束时间
    valueRangePicker: undefined, //时间范围
  }) //获取知识库文件列表表单
  const modalTitle = ref('') //对话框title
  const commonKnowledgeBase = ref([]) //常用知识库
  const fileList = ref([]) //上传文件列表
  const fileListFolder = ref([]) //上传文件夹列表
  const rootUrl = import.meta.env.VITE_APP_URL
  const dataUploadTheKnowledgeBaseFile = ref({
    documentId: undefined,
    filePath: undefined,
  }) //上传文件参数
  const disabledUploadTheKnowledgeBaseFile = ref(true)
  const headers = ref({})
  const openCreateFileModal = ref(false) //创建文件对话框状态
  const infoCreateFileModal = ref(undefined) //创建文件对话框info
  onMounted(() => {
    //设置请求头
    function getCookie(name) {
      const cookies = document.cookie.split(';')
      for (let cookie of cookies) {
        const [key, value] = cookie.trim().split('=')
        if (key === name) {
          return decodeURIComponent(value)
        }
      }
      return null // 未找到
    }
    const env = import.meta.env.VITE_APP_ENV
    let allCookies
    if (env === 'dev') {
      allCookies =
        'Online.3c9e656d1f13e0fc2cbc3af658e20243.a2ea35f3dbdc77be94b2a95c4f0464ad.eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJYTUdleUoxYzJWeVRtRnRaU0k2SW5sMWJuZGxhU0lzSW1sa0lqb2lNelFpTENKeVpXZHBiMjVKWkNJNklqQWlMQ0pwY0VGa1pISmxjM01pT2lJeE56SXVNVFl1TWpVMExqSXlJbjA9R0lDViIsImp0aSI6IjM5MzE3MiIsImlhdCI6MTc1MzkyNDA2N30.q46CDRGEWL8-Xc_iQGd1am8xHEa-a9FQhWU45WIbLGslEj93I4yU6ASgWEz7O7iZhu-ZzGYRHQH-pIv65LBFyg; Path=/; SameSite=Lax;'
    } else if (env === 'pro') {
      allCookies = getCookie('X-Subject-Token')
    }
    headers.value = {
      authorization: `Bearer ${allCookies}`,
    }
    getKnowledgeBaseFolderList(formKnowledgeBaseFolder.value)
    getCommonKnowledgeBase()
    getKnowledgeBaseFileList(formKnowledgeBaseFileList.value)
  })
  watch(
    selectedKeys,
    (value) => {
      disabledUploadTheKnowledgeBaseFile.value = value[0] === 0 ? true : false
    },
    {
      deep: true,
      immediate: true,
    }
  )
  // 自定义方法
  //更新页面
  const updatePage = () => {
    getKnowledgeBaseFileList(formKnowledgeBaseFileList.value)
  }
  //获取文件url
  const getFileUrl = async (data) => {
    const res = await api.getFileUrl(data)
    window.open(res.data.data, '_blank')
  }
  //获取知识库文件夹列表
  const getKnowledgeBaseFolderList = async (data) => {
    const res = await api.getKnowledgeBaseFolderList(data)
    const fun = (list) => {
      list.forEach((item) => {
        item.title = item.name
        item.key = item.id
        if (item.children.length > 0) {
          fun(item.children)
        } else {
          return
        }
      })
    }
    fun(res.data.data)
    treeData.value = [
      {
        key: 0,
        title: '全部',
        children: res.data.data,
      },
    ]
  }
  //新增知识库文件夹列表
  const addKnowledgeBaseFolderList = async (data) => {
    const res = await api.addKnowledgeBaseFolderList(data)
    if (res.data.code === 200) {
      message.success('新增成功')
      clickModalCancel()
      getKnowledgeBaseFolderList(formKnowledgeBaseFolder.value)
    } else {
      message.error('新增失败')
    }
  }
  //编辑知识库文件夹列表
  const editKnowledgeBaseFolderList = async (data) => {
    const res = await api.editKnowledgeBaseFolderList(data)
    if (res.data.code === 200) {
      message.success('编辑成功')
      clickModalCancel()
      getKnowledgeBaseFolderList(formKnowledgeBaseFolder.value)
    } else {
      message.error('编辑失败')
    }
  }
  //删除知识库文件夹列表
  const delKnowledgeBaseFolderList = async (data) => {
    const res = await api.delKnowledgeBaseFolderList(data)
    if (res.data.code === 200) {
      message.success('删除成功')
      getKnowledgeBaseFolderList(formKnowledgeBaseFolder.value)
    } else {
      message.error('删除失败')
    }
  }
  //获取常用知识库
  const getCommonKnowledgeBase = async () => {
    const res = await api.getCommonKnowledgeBase()
    console.log('获取常用知识库', res)
    commonKnowledgeBase.value = res.data.data
  }
  //文件批量下载
  const batchDownloadFiles = async (data) => {
    const res = await api.batchDownloadFiles(data)
    console.log('文件批量下载', res)
    if (res.status === 200) {
      commonMethod.derive(res)
    } else {
      message.error(res.data.msg)
    }
  }
  //获取知识库文件列表
  const getKnowledgeBaseFileList = async (data) => {
    const res = await api.getKnowledgeBaseFileList(data)
    console.log('获取知识库文件列表', res)
    tableData.value = res.data.data.records
    formKnowledgeBaseFileList.value.total = res.data.data.total
  }
  //新增或移除个人收藏
  const addOrRemovePersonalCollections = async (data) => {
    const res = await api.addOrRemovePersonalCollections(data)
    console.log('新增或移除个人收藏', res)
    if (res.data.code === 200) {
      message.success('操作成功')
      getKnowledgeBaseFileList(formKnowledgeBaseFileList.value)
    } else {
      message.error('操作失败')
    }
  }

  //删除知识库文件
  const delKnowledgeBaseFileList = async (data) => {
    const res = await api.delKnowledgeBaseFileList(data)
    if (res.data.code === 200) {
      message.success('删除成功')
      getKnowledgeBaseFileList(formKnowledgeBaseFileList.value)
    } else {
      message.error('删除失败')
    }
  }
  //增加知识库使用次数
  const increaseUsageFrequencyKnowledgeBase = async (data) => {
    const res = await api.increaseUsageFrequencyKnowledgeBase(data)
    if (res.data.code === 200) {
      getCommonKnowledgeBase()
    }
  }
  //点击查询文件夹目录
  const clickQueryKnowledgeBaseFolder = () => {
    getKnowledgeBaseFolderList(formKnowledgeBaseFolder.value)
  }
  //点击添加文件夹目录
  const clickAddKnowledgeBaseFolder = (value, key, title) => {
    console.log('点击添加文件夹目录', value, key)
    modalTitle.value = value
    openFolder.value = true
    if (value === '新增') {
      formAddEditKnowledgeBaseFolder.value.parentId = key
    } else if (value === '编辑') {
      formAddEditKnowledgeBaseFolder.value.id = key
      formAddEditKnowledgeBaseFolder.value.name = title
    }
  }
  //点击删除文件夹目录
  const clickDelKnowledgeBaseFolder = (key) => {
    delKnowledgeBaseFolderList([key])
  }
  //点击对话框确定
  const clickModalOk = () => {
    if (modalTitle.value === '新增') {
      addKnowledgeBaseFolderList(formAddEditKnowledgeBaseFolder.value)
    } else if (modalTitle.value === '编辑') {
      editKnowledgeBaseFolderList(formAddEditKnowledgeBaseFolder.value)
    }
  }
  //点击对话框取消
  const clickModalCancel = () => {
    openFolder.value = false
    formAddEditKnowledgeBaseFolder.value = {
      id: undefined,
      parentId: undefined,
      name: undefined,
      documentType: 1,
    }
  }
  //点击树节点
  const clickTreeNode = (
    selectedKeys,
    { selected, selectedNodes, node, event }
  ) => {
    listTitle.value = node.title
    dataUploadTheKnowledgeBaseFile.value.documentId = node.id
    infoCreateFileModal.value = node.id
    if (node.id === 0) {
      formKnowledgeBaseFileList.value.documentId = undefined
    } else {
      formKnowledgeBaseFileList.value.documentId = node.id
    }
    getKnowledgeBaseFileList(formKnowledgeBaseFileList.value)
  }
  //上传知识库文件改变
  const changeUploadTheKnowledgeBaseFileUrl = (info) => {
    if (info.file.status === 'done') {
      message.success(`上传成功`)
      getKnowledgeBaseFileList(formKnowledgeBaseFileList.value)
      getKnowledgeBaseFolderList(formKnowledgeBaseFolder.value)
    } else if (info.file.status === 'error') {
      message.error(`上传失败`)
    }
  }
  //上传文件夹之前
  const beforeUploadFolder = (file, fileList) => {
    dataUploadTheKnowledgeBaseFile.value.filePath = file.webkitRelativePath
  }
  //上传文件夹改变
  const changeUploadFolder = (info) => {
    console.log('info', info)
    if (info.file.status === 'done') {
      message.success(`上传成功`)
      getKnowledgeBaseFileList(formKnowledgeBaseFileList.value)
      getKnowledgeBaseFolderList(formKnowledgeBaseFolder.value)
    } else if (info.file.status === 'error') {
      message.error(`上传失败`)
    }
  }
  //分页改变
  const changePagination = () => {
    getKnowledgeBaseFileList(formKnowledgeBaseFileList.value)
  }
  //时间范围改变
  const changeRangePicker = (date, strDate) => {
    formKnowledgeBaseFileList.value.startTime = strDate[0]
    formKnowledgeBaseFileList.value.endTime = strDate[1]
  }
  //点击重置
  const clickReset = () => {
    formKnowledgeBaseFileList.value = {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      documentId: undefined,
      fileName: undefined, //文件名称
      createBy: undefined, //创建人
      startTime: undefined, //开始时间
      endTime: undefined, //结束时间
      valueRangePicker: undefined, //时间范围
    }
    getKnowledgeBaseFileList(formKnowledgeBaseFileList.value)
  }
  //点击查询
  const clickQuery = () => {
    getKnowledgeBaseFileList(formKnowledgeBaseFileList.value)
  }
  //点击查看下载删除收藏
  const clickOperation = (value, record) => {
    console.log('点击查看下载删除收藏', value, record)
    if (value === '下载') {
      increaseUsageFrequencyKnowledgeBase({ id: record.id })
      batchDownloadFiles({
        fileIds: [record.fileId],
        fileName: record.fileName,
      })
    } else if (value === '查看') {
      increaseUsageFrequencyKnowledgeBase({ id: record.id })
      api.getFileUrl({ fileId: record.fileId }).then((res) => {
        let fileType = record.fileName.split('.').at(-1)
        const routeData = router.resolve({
          path: '/only-office-editor',
          query: {
            type: 'view',
            fileUrl: res.data.data,
            fileId: record.fileId,
            title: record.fileName,
            fileType,
          },
        })
        window.open(routeData.href, '_blank') // 在新窗口打开
      })
    } else if (value === '收藏') {
      addOrRemovePersonalCollections({ id: record.id })
    } else if (value === '删除') {
      delKnowledgeBaseFileList([record.id])
    } else if (value === '编辑') {
      api.getFileUrl({ fileId: record.fileId }).then((res) => {
        let fileType = record.fileName.split('.').at(-1)
        const routeData = router.resolve({
          path: '/only-office-editor',
          query: {
            type: 'edit',
            fileUrl: res.data.data,
            fileId: record.fileId,
            title: record.fileName,
            fileType,
          },
        })
        window.open(routeData.href, '_blank') // 在新窗口打开
      })
    }
  }
  //点击新建文件
  const clickCreateFile = () => {
    openCreateFileModal.value = true
  }
  //关闭新建文件对话框
  const cancelCreateFileModal = () => {
    openCreateFileModal.value = false
  }
</script>
<style lang="less" scoped>
  .document-management {
    .row-one {
      margin-bottom: (20 / @vh);
      .row-one-box {
        display: flex;
        flex-wrap: wrap;
        gap: (20 / @vw);
        .item {
          display: flex;
          align-items: center;
          padding: (24 / @vh) (24 / @vw);
          width: 18%;
          color: #3d3d3d;
          font-size: (16 / @vw);
          border: 1px solid rgba(0, 0, 0, 0.06);
          border-radius: (8 / @vw);
          cursor: pointer;
          box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.06);
          &:hover {
            color: @tc;
            border-color: @tc;
          }
          .icon {
            margin-right: (10 / @vw);
            font-size: (20 / @vw);
          }
          .text {
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
    .row-two {
      display: flex;
      .row-two-left {
        margin-right: (20 / @vw);
        .input-box {
          display: flex;
          margin-bottom: (10 / @vh);
          .input {
            margin-right: (10 / @vw);
          }
          .button {
            margin-right: (10 / @vw);
          }
        }
        .tree-item {
          display: inline-block;
          .icon {
            margin-right: (10 / @vw);
            cursor: pointer;
            opacity: 0.2;
            &:hover {
              opacity: 1;
            }
            &:last-child {
              margin-right: 0;
            }
          }
        }
      }
      .row-two-right {
        flex: 1;
        .query {
          margin-bottom: (20 / @vh);
          .input-box {
            display: flex;
            justify-content: space-between;
            // flex-wrap: wrap;
            gap: (20 / @vw);
            .item {
              display: flex;
              align-items: center;
              .text {
                margin-right: (10 / @vw);
                text-align: right;
              }
              .input {
                flex: 1;
              }
              .picker {
                width: (300 / @vw);
              }
              .button {
                margin-right: (10 / @vw);
              }
            }
            .item-time {
              width: 40%;
            }
          }
        }
        .list {
          .button-box {
            display: flex;
            .button {
              margin-right: (10 / @vw);
              &:last-child {
                margin-right: 0;
              }
            }
          }
          .table {
            margin-bottom: (20 / @vh);
            .operation {
              span {
                margin-right: (10 / @vw);
                color: @tc;
                cursor: pointer;
                &:last-child {
                  margin-right: 0;
                }
              }
            }
          }
        }
      }
    }
    .modal {
      .item {
        display: flex;
        align-items: center;
        .label {
          margin-right: (10 / @vw);
          width: (100 / @vw);
          text-align: right;
        }
        .input {
          flex: 1;
        }
      }
    }
  }
</style>
